package com.noahplat.device.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.common.utils.NoahEnum;
import com.noahplat.common.utils.RedisUtils;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.datapro.feign.DataProFeign;
import com.noahplat.device.mapper.DeviceMapper;
import com.noahplat.device.mapper.ModelMapper;
import com.noahplat.device.mapper.TypeMapper;
import com.noahplat.device.pojo.Device;
import com.noahplat.device.pojo.Model;
import com.noahplat.device.pojo.Type;
import com.noahplat.device.service.DeviceService;
import com.noahplat.device.util.CountDao;
import com.noahplat.user.feign.AccountFeign;
import com.noahplat.user.pojo.Account;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DeviceServiceImpl
 * @Description: 设备实现类
 * @Author 李景星
 * @Date 2021/3/9
 * @Version 1.0
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private DataProFeign dataProFeign;
    @Autowired
    private AccountFeign accountFeign;

    /**
     * 获取设备详情
     * @param imei
     * @return
     */
    @Override
    public Result<Device> getDevice(String imei) {
        //获取设备信息
        Example deviceExample = new Example(Device.class);
        deviceExample.createCriteria().andEqualTo("imei", imei);
        Device device = deviceMapper.selectOneByExample(deviceExample);
        if(ObjectUtils.isEmpty(device)){
            return new Result(false, StatusCode.ERROR, "暂无该设备信息");
        }
        //封装设备型号和设备型号示例图片
        if(!ObjectUtils.isEmpty(device.getModelid())){
            if(redisUtils.hasKey(NoahEnum.MODELDIR.getCode()+NoahEnum.MODELKEY.getCode())){
                List<Model> list = (List<Model>)(List)redisUtils.lGet(NoahEnum.MODELDIR.getCode() + NoahEnum.MODELKEY.getCode(), 0, -1);
                for (Model model : list) {
                    if(device.getModelid() == model.getId()){
                        device.setModel(model.getPromodel());
                        device.setImage(model.getImage());
                    }
                }
            }else {
                Model model = modelMapper.selectByPrimaryKey(device.getModelid());
                device.setModel(model.getPromodel());
                device.setImage(model.getImage());
            }
        }
        //封装设备类型
        if(!ObjectUtils.isEmpty(device.getTypeid())){
            if(redisUtils.hasKey(NoahEnum.TYPEDIR.getCode()+NoahEnum.TYPEKEY.getCode())){
                List<Type> list = (List<Type>)(List)redisUtils.lGet(NoahEnum.TYPEDIR.getCode()+NoahEnum.TYPEKEY.getCode(), 0, -1);
                for (Type type : list) {
                    if(device.getTypeid() == type.getId()){
                        device.setType(type.getType());
                    }
                }
            }else {
                Type type = typeMapper.selectByPrimaryKey(device.getTypeid());
                device.setType(type.getType());
            }
        }
        return new Result<Device>(true, StatusCode.OK, "查询成功", device);
    }

    /**
     * 条件查询设备信息
     * @param page
     * @param limit
     * @param dealer
     * @param imei
     * @return
     */
    @Override
    public Result getDevices(Integer page,Integer limit,Long dealer,String imei){
        PageHelper.startPage(page,limit);
        List<Device> list = new ArrayList<>();
        if(StringUtils.isEmpty(imei)){
            list = deviceMapper.getDeviceByDealer(dealer);
        }else {
            list = deviceMapper.getDeviceByImei(dealer,imei);
        }
        if(ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.NOTFOUNDERROR,"无设备信息");
        }
        PageInfo<Device> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * 查找定位设备
     * @param page
     * @param limit
     * @param dealer
     * @param imei
     * @return
     */
    public Result getSiteDevices(Integer page,Integer limit,Long dealer,String imei){
        PageHelper.startPage(page,limit);
        List<Device> list = new ArrayList<>();
        if(StringUtils.isEmpty(imei)){
            list = deviceMapper.getSiteDeviceByDealer(dealer);
        }else {
            list = deviceMapper.getSiteDeviceByImei(dealer,imei);
        }
        if(ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.NOTFOUNDERROR,"无设备信息");
        }
        PageInfo<Device> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * 根据ID查询设备信息
     * @param id
     * @return
     */
    @Override
    public Result getDeviceAllInfoById(Long id){
        Example example = new Example(Device.class);
        example.createCriteria().orEqualTo("id",id);
        Device device = deviceMapper.selectOneByExample(example);
        if(ObjectUtils.isEmpty(device)){
            return new Result(false,StatusCode.NOTFOUNDERROR,"暂无该设备信息");
        }
        //封装设备型号和设备型号示例图片
        if(!ObjectUtils.isEmpty(device.getModelid())){
            if(redisUtils.hasKey(NoahEnum.MODELDIR.getCode()+NoahEnum.MODELKEY.getCode())){
                List<Model> list = (List<Model>)(List)redisUtils.lGet(NoahEnum.MODELDIR.getCode() + NoahEnum.MODELKEY.getCode(), 0, -1);
                for (Model model : list) {
                    if(device.getModelid() == model.getId()){
                        device.setModel(model.getPromodel());
                        device.setImage(model.getImage());
                    }
                }
            }else {
                Model model = modelMapper.selectByPrimaryKey(device.getModelid());
                device.setModel(model.getPromodel());
                device.setImage(model.getImage());
            }
        }
        //封装设备类型
        if(!ObjectUtils.isEmpty(device.getTypeid())){
            if(redisUtils.hasKey(NoahEnum.TYPEDIR.getCode()+NoahEnum.TYPEKEY.getCode())){
                List<Type> list = (List<Type>)(List)redisUtils.lGet(NoahEnum.TYPEDIR.getCode()+NoahEnum.TYPEKEY.getCode(), 0, -1);
                for (Type type : list) {
                    if(device.getTypeid() == type.getId()){
                        device.setType(type.getType());
                    }
                }
            }else {
                Type type = typeMapper.selectByPrimaryKey(device.getTypeid());
                device.setType(type.getType());
            }
        }
        String[] imeis = {device.getImei()};
        String[] types = {NoahEnum.STEP.getCode(),NoahEnum.BLOOD.getCode(),NoahEnum.HEART.getCode(),NoahEnum.TEMP.getCode(),
                NoahEnum.SITE.getCode(),NoahEnum.SP.getCode()};
        Result result = dataProFeign.getReal(imeis,types);
        if(!result.isFlag()){
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
        List<Map> list = (List<Map>) result.getData();
        for(Map map : list){
            if(!ObjectUtils.isEmpty(map.get("blood"))){
                device.setBlood(map.get("blood").toString());
            }
            if(!ObjectUtils.isEmpty(map.get("heart"))){
                device.setHeart(map.get("heart").toString());
            }
            if(!ObjectUtils.isEmpty(map.get("step"))){
                device.setStep(map.get("step").toString());
            }
            if(!ObjectUtils.isEmpty(map.get("sp"))){
                device.setSp(map.get("sp").toString());
            }
            if(!ObjectUtils.isEmpty(map.get("site"))){
                device.setSiteTime((Date) map.get("siteTime"));
                device.setSite(map.get("site").toString());
            }
        }

        return new Result<Device>(true, StatusCode.OK, "查询成功", device);
    }

    /**
     * 查询设备数量
     * @param dealer
     * @return
     */
    @Override
    public Result getDeviceCount(Long dealer){
        Example example = new Example(Device.class);
        example.createCriteria().orEqualTo("dealer",dealer);
        int count = deviceMapper.selectCountByExample(example);
        return new Result(true,StatusCode.OK,"查询成功",count);
    }

    /**
     * 分页查询设备数量
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getDeviceByDealer(Integer page,Integer limit){
        PageHelper.startPage(page,limit);
        List<CountDao> list = deviceMapper.selectDeviceCount();
        if(ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.ERROR,"暂无数据");
        }
        Result result = accountFeign.getAccounts();
        if(!result.isFlag()){
            return new Result(false,StatusCode.ERROR,"获取账套信息失败");
        }
        List<Map> list1 = (List<Map>) result.getData();
        for(CountDao countDao : list){
            for(Map map : list1){
                if(countDao.getDealer() == Integer.parseInt(map.get("id").toString())){
                    countDao.setAccount(map.get("acctname").toString());
                    break;
                }
            }
        }
        PageInfo<CountDao> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * 批量添加设备信息
     * @param file
     * @param type
     * @return
     */
    @Override
    public Result addExcel(MultipartFile file, String type) {
        List<Device> list = new ArrayList<>();
        String fileName = file.getOriginalFilename();
        Workbook workbook = null;
        try{
            InputStream inputStream = file.getInputStream();
            if(fileName.endsWith("xls")){
                workbook = new HSSFWorkbook(inputStream);
            }else {
                workbook = new XSSFWorkbook(inputStream);
            }
            Sheet sheet = workbook.getSheetAt(0);
            int rowLength = sheet.getLastRowNum() + 1;
            Row row = sheet.getRow(0);
            int colLength = row.getLastCellNum();
            Cell cell = row.getCell(0);
            for(int i = 1;i < rowLength;i++){
                row = sheet.getRow(i);
                Device device = new Device();
                for(int j = 0;j < colLength;j++){
                    cell = row.getCell(j);
                    if(cell !=null){
                        cell.setCellType(CellType.STRING);
                        String data = cell.getStringCellValue();
                        data = data.trim();
                        switch (j){
                            case 0:
                                device.setImei(data);
                                break;
                            case 1:
                                device.setDealer(Long.parseLong(data));
                                break;
                            case 2:
                                device.setProd(data);
                                break;
                            case 3:
                                device.setModelid(Long.parseLong(data));
                                break;
                            case 4:
                                device.setTypeid(Long.parseLong(data));
                                break;
                            case 5:
                                if(type.equals("0")){//随机生成激活码
                                    device.setDevcode(String.valueOf((Math.random()*9+1)*100000));
                                }else {
                                    device.setDevcode(data);
                                }
                                break;
                            case 6:
                                device.setSupLocation(data);
                                break;
                            case 7:
                                device.setSupTemp(data);
                                break;
                            case 8:
                                device.setSupHeart(data);
                                break;
                            case 9:
                                device.setSupBlood(data);
                                break;
                            case 10:
                                device.setSupSleep(data);
                                break;
                            case 11:
                                device.setSupStep(data);
                                break;
                            case 12:
                                device.setSupOxygen(data);
                                break;
                            default:
                                break;
                        }
                    }
                }
                device.setCreateTime(new Date());
                list.add(device);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        int res = deviceMapper.insertDevice(list);
        if(res == 0){
            return new Result(false,StatusCode.ERROR,"添加失败");
        }
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /**
     * 单条添加设备
     * @param device
     * @return
     */
    @Override
    public Result addDevice(Device device){
        device.setCreateTime(new Date());
        int res = deviceMapper.insert(device);
        if(res == 0){
            return new Result(false,StatusCode.ERROR,"添加失败");
        }
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /**
     * 修改设备信息
     * @param device
     * @return
     */
    @Override
    public Result updateDevice(Device device){
        int res = deviceMapper.updateByPrimaryKeySelective(device);
        if(res == 0){
            return new Result(false,StatusCode.ERROR,"修改失败");
        }
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /**
     * 条件查询设备信息
     * @param dealer
     * @param imei
     * @param prod
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getAdminDevice(Long dealer,String imei,String prod,Integer page,Integer limit){
        PageHelper.startPage(page,limit);
        Example example = new Example(Device.class);
        example.createCriteria().andEqualTo("dealer",dealer).andEqualTo("imei",imei).andEqualTo("prod",prod);
        List<Device> list = deviceMapper.selectByExample(example);
        if(ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.ERROR,"暂无数据");
        }
        PageInfo<Device> pageInfo = new PageInfo<>(list);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     *redis维护工地项目人员
     * @param imei
     * @return
     */
    @Override
    public Result addWorkerSite(String imei){
        boolean res = redisUtils.set(NoahEnum.WORKERSITE.getCode() + imei,imei);
        if (!res){
            return new Result(false,StatusCode.ERROR,"添加报错");
        }
        return new Result(true,StatusCode.OK,"添加成功");
    }
}
